package com.zcsy.seller.web.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.util.Globals;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.common.CommonService;
import com.zcsy.manage.service.system.IMenuService;
import com.zcsy.manage.service.system.IRoleService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.seller.web.common.LogUtils;

/**
 * 
 * @Title: LoginController.java
 * @Package： com.zcsy.manage.web.system 
 * @Description: 登陆方法
 * @author chensf 735569870@qq.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年1月8日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
public class LoginController {

	/**
	 * 日志创建对象<br>
	 */
	private static final Log log = LogFactory.getLog(LoginController.class);
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IMenuService menuService;
	
	@Autowired
	private IRoleService roleService;
	
//	@Autowired
//	private RoleDao roleDao;
//	
//	@Autowired
//	private UserDao userDao;
	
	@Autowired
	private IShopInfoService shopInfoService;
	
	@RequestMapping(value="login" , method = RequestMethod.GET)
	@ResponseBody
	public RequestJson login(String uname,String pwd,HttpServletRequest request,
			HttpServletResponse response) {
		final HttpSession session = request.getSession();
		RequestJson result = new RequestJson();
		try {
			//验证登录名和手机号
			User loginUser = new User();
			loginUser.setPhone(uname);
			loginUser.setUserType(Constants.BUSINESS_TYPE);
			User user = userService.userLogin(loginUser);
			//取出当前用户在当前小区的roleList角色集合
			if (user == null) {
			 	result.setMsg("用户不存在");
			 	result.setSuccess(false);
			 	return result;
			}
			
			if(user.getState().intValue() != 1){
				result.setMsg("用户已停用");
				result.setSuccess(false);
			 	return result;
			}
			
			//前台用手机号或登录名加密的，但是数据库是用登录名加密存储的，所以要筛除掉手机号的情况
//			pwd = DESEncryption.decrypt(pwd, uname);
//			pwd = DESEncryption.encrypt(pwd, user.getLoginname());
//			final String userKey = MD5Util.generalPassword(user.getLoginname(), pwd);
			//密码校验
			if(pwd.equals(user.getPwd())){
				//取到用户对应的角色id集合放入roleList
				List<String> roleList = userService.selectRoleByUserId(user.getId());
				user.setRoleList(roleList);
				if (CollectionUtils.isEmpty(user.getRoleList())){
				 	result.setMsg("您没有任何权限，请联系管理员");
				 	result.setSuccess(false);
				 	return result;
				}
				
				//根据当前用户的角色list取出每个roleId对应的cellList取并集存入cellInfos
				List<CellInfo> cellInfos = new ArrayList<CellInfo>();
				cellInfos = roleService.getCellInfosByRoleId(user.getRoleList());
				//没有任何小区
				if (CollectionUtils.isEmpty(cellInfos)){
				 	result.setMsg("您没有任何小区的管理权限，请联系管理员");
				 	result.setSuccess(false);
				 	return result;
				}
				user.setCellInfos(cellInfos);

				//修改用户登录次数和登录时间
				userService.updateLoginTimeAndTimes(user);
				
				result.setSuccess(true);
				result.setObj(user);
				result.setMsg("校验通过");
				session.setMaxInactiveInterval(RequestConstants.SessionActionTime);		//设置session超时时间
				session.setAttribute(RequestConstants.USER_SESSION_ID, user);
				session.setAttribute(RequestConstants.IMAGE_LOGO, Globals.getImageUrl());
				LogUtils.insertLog("用户登录",user.getId(),request);
				
			}else{
				result.setMsg("密码错误");
				result.setSuccess(false);
			}
			
		} catch (Exception e) {
		    e.printStackTrace();
			result.setMsg(RequestConstants.NET_ERROR);
			result.setSuccess(false);
		}
		return result;
	}
	
	@RequestMapping(value="getMenuByShopId" , method = RequestMethod.GET)
	@ResponseBody
	public RequestJson getMenuByShopId(String shopId,HttpServletRequest request,HttpServletResponse response) {
		RequestJson result = new RequestJson();
		final HttpSession session = request.getSession();
		User user = CommonService.getSessionUser();
		
		if(user != null){
			ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(shopId);
			if(shopInfo != null && shopInfo.getCellId() != null && shopInfo.getCellId() != ""){
				if(shopInfo.getState() != null && shopInfo.getState() != Constants.SHOP_STATE_DISABLE){
					//取出当前用户在当前小区的roleList角色集合
					if(menuService.updateUserFirstMenuBycell(user , Constants.SYSTEM_BUSINESS , shopInfo.getCellId())){
						CommonService.setSessionUser(user);
						CommonService.setSessionMenus(user.getCellMenus());
						session.setAttribute(RequestConstants.SHOP_ID, shopInfo);
					}else{
						result.setSuccess(false);
						result.setMsg("不好意思，你没有此权限，请选择其他店铺！");
					}
				} else {
					result.setSuccess(false);
					result.setMsg("该店铺已被禁用！");
				}
			} else {
				result.setSuccess(false);
				result.setMsg("该店铺不存在！");
			}
		}else{
			result.setSuccess(false);
			result.setMsg("不好意思，你没有此权限，请选择其他店铺！");
		}
		
		return result;
	}
	
	@RequestMapping(value="exist" , method = RequestMethod.GET)
    @ResponseBody
	public RequestJson logout(HttpServletRequest request,HttpServletResponse response) {
	    RequestJson result = new RequestJson();
	    
		final HttpSession session = request.getSession();
		User user = (User)session.getAttribute(RequestConstants.USER_SESSION_ID);
		LogUtils.insertLog("用户退出",user.getId(),request);
		session.setAttribute(RequestConstants.USER_SESSION_ID, null);
		//退出之前清除与当前用户关联的小区seesion
		if(session.getAttribute("roleCells") != null && session.getAttribute("roleCells") != ""){
			session.removeAttribute("roleCells");
		}
		session.invalidate();
		return result;
	}
	
    @RequestMapping(value="selectShop" , method = RequestMethod.GET)
    public String cellInfoList(Model model, Integer pNo,HttpServletRequest request){
	    if(pNo == null){
            pNo = Constants.PAGE_NO;
        }
	    
        //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, 5);
        
		final HttpSession session = request.getSession();
		User user = (User)session.getAttribute(RequestConstants.USER_SESSION_ID);

		//获取当前商户拥有哪些店铺，以及店铺所在小区（店铺id已去重）
		List<Map<String, Object>> shopIdList = shopInfoService.getCellIdListByBusiAccountId(user.getId());
		
        PageInfo<Map<String, Object>> info = new PageInfo<Map<String, Object>>(shopIdList);
	    model.addAttribute("shopList", info);
		model.addAttribute("currentPage", pNo);
        
        return "selectShop";
    }
}
